<template>
  <mi-header></mi-header>
  <div class="shoppingCart">
      <!-- 购物车头部 -->
      <div class="cart-header">
        <div class="cart-header-content">
          <p>
            <i class="el-icon-shopping-cart-full" style="color:#ff6700; font-weight: 600;"></i>
            我的购物车
          </p>
          <span>温馨提示：产品是否购买成功，以最终下单为准，请尽快结算</span>
        </div>
      </div>
      <!-- 购物车头部END -->

      <!-- 购物车主要内容区 -->
      <div class="content" v-if="this.shoppingCart.length>0">
        <ul>
          <!-- 购物车表头 -->
          <li class="header">
            <div class="pro-check">
              <el-checkbox @click="isAllCheck">全选</el-checkbox>
            </div>
            <div class="pro-img"></div>
            <div class="pro-name">商品名称</div>
            <div class="pro-price">单价</div>
            <div class="pro-num">数量</div>
            <div class="pro-total">小计</div>
            <div class="pro-action">操作</div>
          </li>
          <!-- 购物车表头END -->

          <!-- 购物车列表 -->
          <li class="product-list" v-for="(item,index) in shoppingCart" :key="item.id">
            <div class="pro-check">
              <el-checkbox :value="item.check" @click="checkChange($event,item.id)"></el-checkbox>
            </div>
            <div class="pro-img">
              <router-link :to="{ name: 'product', params: {productId:item.productId} }">
                <img :src="item.pic_urls" />
              </router-link>
            </div>
            <div class="pro-name">
              <router-link
                :to="{ name: 'product', params: {productId:item.productId} }"
              >{{item.productName}}</router-link>
            </div>
            <div class="pro-price">{{item.price}}元</div>
            <div class="pro-num">
              <el-input-number
                v-model="item.num"
                size="small"
                :min="1"
                @input="handleChange($event,index,item.productId)"
                :max="item.maxNum"
              ></el-input-number>
              <!--<el-input v-model.number="item.num" placeholder="订单号" @input="orderNoChange"></el-input>-->
            </div>
            <div class="pro-total pro-total-in">{{item.price*item.num}}元</div>
            <div class="pro-action">
              <i class="el-icon-error" style="font-size: 18px;" @click="deleteItem($event,item.id,item.productId)"></i>
            </div>
          </li>
          <!-- 购物车列表END -->
        </ul>
        <div style="height:20px;background-color: #f5f5f5"></div>
        <!-- 购物车底部导航条 -->
        <div class="cart-bar">
          <div class="cart-bar-left">
          <span>
            <router-link to="/goods">继续购物</router-link>
          </span>
            <span class="sep">|</span>
            <span class="cart-total">
            共
            <span class="cart-total-num">{{this.shoppingCart.length}}</span> 件商品，已选择
            <span class="cart-total-num">{{getCheckNum()}}</span> 件
          </span>
          </div>
          <div class="cart-bar-right">
          <span>
            <span class="total-price-title">合计：</span>
            <span class="total-price">{{getTotalPrice()}}元</span>
          </span>
            <div :class="getCheckNum() > 0 ? 'btn-primary' : 'btn-primary-disabled'" @click="setSelectedGoods()">去结算</div>
          </div>
        </div>
        <!-- 购物车底部导航条END -->
      </div>
      <!-- 购物车主要内容区END -->

      <!-- 购物车为空的时候显示的内容 -->
      <div v-else class="cart-empty">
        <div class="empty">
          <h2>您的购物车还是空的！</h2>
          <p>快去购物吧！</p>
        </div>
      </div>
      <!-- 购物车为空的时候显示的内容END -->
    <!--分页-->
    <div class="page-bar clearfix">
      <ul>
        <li v-if="cur > 1">
          <a v-on:click="cur--, pageClick()">上一页</a>
        </li>
        <li v-if="cur == 1"><a class="banclick">上一页</a></li>
        <li
          :key="index"
          v-for="index in indexs"
          v-bind:class="{ active: cur == index }"
        >
          <a v-on:click="btnClick(index)">{{ index }}</a>
        </li>
        <li v-if="cur != all">
          <a v-on:click="cur++, pageClick()">下一页</a>
        </li>
        <li v-if="cur == all"><a class="banclick">下一页</a></li>
        <li>
          <a
          >共<i>{{ all }}</i
          >页</a
          >
        </li>
      </ul>
    </div>
    </div>
  <mi-footer></mi-footer>
</template>

<script>
import MiFooter from '@/components/MiFooter'
import MiHeader from '@/components/MiHeader'
import axios from 'axios'
export default {
  name: 'Cart',
  components: {
    MiFooter,
    MiHeader
  },
  data () {
    return {
      all: 10, // 总页数
      cur: 1, // 当前页码
      totalPage: 0, // 当前条数
      userId: 123,
      shoppingCart: [
        {
          id: '1',
          productId: '12',
          productName: 'iphone13',
          pic_urls: 'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1621955784.84614979.jpg',
          price: '9500',
          num: 1,
          maxNum: 3,
          check: true
        },
        {
          id: '2',
          productId: '12',
          productName: '小米13',
          pic_urls: 'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1621955784.84614979.jpg',
          price: '3500',
          num: 2,
          maxNum: 3,
          check: false
        }
      ]
      /*
        shoppingCart = {
          id: "", // 购物车id
          productId: "", // 商品id
          productName: "", // 商品名称
          pic_urls: "", // 商品图片
          price: "", // 商品价格
          num: "", // 商品数量
          maxNum: "", // 商品限购数量
          check: false // 是否勾选
        } */
    }
  },
  created () {
    this.onLoad()
  },
  methods: {
    async onLoad () {
      await axios.get(`http://localhost:8088/order/getShoppingCartInfo?pageNo=${this.cur}&userId=${this.userId}&pageSize=2`).then((res) => { this.shoppingCart = res.data.shoppingCart; this.all = res.data.allPage; this.totalPage = res.data.pageSize; this.cur = res.data.curPageNo })
      console.log(this.shoppingCart)
    },
    // 这是一个定时器
    timer () {
      return setTimeout(() => {
        this.getData()
      }, 5000)
    },
    watch: {
      list () {
        this.timer()
      }
    },
    destroyed () {
      clearTimeout(this.timer)
    },
    // 请求数据
    dataListFn: function (index) {
      axios.get('http://localhost:8088/order/getShoppingCartInfo',
        {
          params: {
            pageNo: index,
            userId: this.userId,
            pageSize: '2'
          }
        }).then((res) => {
        if (res.data.code === '000') {
          this.all = res.data.allPage// 总页数
          this.cur = res.data.curPageNo
          this.totalPage = res.data.pageSize
          this.shoppingCart = res.data.shoppingCart
        }
      })
    },
    // 分页
    btnClick: function (data) { // 页码点击事件
      if (data !== this.cur) {
        this.cur = data
      }
      // 根据点击页数请求数据
      // this.dataListFn(this.cur.toString())
      this.onLoad()
    },
    pageClick: function () {
      // 根据点击页数请求数据
      // this.dataListFn(this.cur.toString())
      this.onLoad()
    },
    // 修改商品数量的时候调用该函数
    handleChange (currentValue, key, productID) {
      console.log('key=' + key, 'productID=' + productID, 'currentValue=' + currentValue)
      // 向后端发起更新购物车的redis信息请求
      axios.post('http://localhost:8088/order/updateShoppinCartForRedis',
        {
          shoppingCart: [
            {
              productId: productID,
              num: currentValue
            }
          ],
          userId: this.userId
        }).then((res) => {
        if (res.data.code === '000') {
          console.log('修改成功')
          alert('修改成功')
        }
      })
    },
    setSelectedGoods () {
      const shoppingCart = []
      for (let i = 0; i < this.shoppingCart.length; i++) {
        const temp = this.shoppingCart[i]
        if (temp.check) {
          shoppingCart.push({ productId: temp.productId, check: true })
        }
      }
      // 向后端发起更新购物车中已选择的商品
      axios.post('http://localhost:8088/order/updateShoppinCartForRedis',
        {
          shoppingCart,
          userId: this.userId
        }).then((res) => {
        if (res.data.code === '000') {
          this.$router.push({ path: '/pay' })
        }
      })
    },
    // 向后端发起删除购物车的redis信息请求
    deleteItem (e, id, productID) {
      console.log('id=' + id, 'pro=' + productID, 'e=' + e)
      this.deleteShoppingCart(id)
      axios.post('http://localhost:8088/order/deleteGoodsFromShoppingCart',
        {
          shoppingCart: [
            {
              productId: productID
            }
          ],
          userId: this.userId
        }).then((res) => {
        if (res.data.code === '000') {
          this.deleteShoppingCart(id)
          alert('删除成功')
        }
      })
    },
    deleteShoppingCart (id) {
      // 根据购物车id删除购物车商品
      for (let i = 0; i < this.shoppingCart.length; i++) {
        const temp = this.shoppingCart[i]
        if (temp.id === id) {
          this.shoppingCart.splice(i, 1)
        }
      }
    },
    checkChange (val, key) {
      // 更新vuex中购物车商品属性信息
      console.log('checkChange-key' + key)
      console.log('checkChange-checkState:' + val.target.checked)
      for (let i = 0; i < this.shoppingCart.length; i++) {
        if (key === this.shoppingCart[i].id) {
          this.shoppingCart[i].check = val.target.checked
        }
      }
      this.getCheckNum()
    },
    isAllCheck () {
      this.checkAll(true)
    },
    checkAll (data) {
      // 点击全选按钮，更改每个商品的勾选状态
      for (let i = 0; i < this.shoppingCart.length; i++) {
        this.shoppingCart[i].check = data
      }
    },
    getCheckNum () {
      // 获取购物车勾选的商品数量
      let totalNum = 0
      for (let i = 0; i < this.shoppingCart.length; i++) {
        const temp = this.shoppingCart[i]
        if (temp.check) {
          totalNum += temp.num
        }
      }
      return totalNum
    },
    getTotalPrice () {
      // 购物车勾选的商品总价格
      let totalPrice = 0
      for (let i = 0; i < this.shoppingCart.length; i++) {
        const temp = this.shoppingCart[i]
        if (temp.check) {
          totalPrice += temp.price * temp.num
        }
      }
      return totalPrice
    }
  },
  computed: {
    // 分页
    indexs: function () {
      var left = 1
      var right = this.all
      var ar = []
      if (this.all >= 5) {
        if (this.cur > 3 && this.cur < this.all - 2) {
          left = this.cur - 2
          right = this.cur + 2
        } else {
          if (this.cur <= 3) {
            left = 1
            right = 5
          } else {
            right = this.all
            left = this.all - 4
          }
        }
      }
      while (left <= right) {
        ar.push(left)
        left++
      }
      return ar
    }
  }
}
</script>

<style>
  * {
    list-style: none;
  }
  .el-icon-error:before {
    content:"\e79d";
  }
  .shoppingCart {
    background-color: #f5f5f5;
    padding-bottom: 20px;
  }
  /* 购物车头部CSS */
  .shoppingCart .cart-header {
    height: 64px;
    border-bottom: 2px solid #ff6700;
    background-color: #fff;
    margin-bottom: 20px;
  }
  .shoppingCart .cart-header .cart-header-content {
    width: 1225px;
    margin: 0 auto;
  }
  .shoppingCart .cart-header p {
    font-size: 28px;
    line-height: 58px;
    float: left;
    font-weight: normal;
    color: #424242;
  }
  .shoppingCart .cart-header span {
    color: #757575;
    font-size: 12px;
    float: left;
    height: 20px;
    line-height: 20px;
    margin-top: 30px;
    margin-left: 15px;
  }
  /* 购物车头部CSS END */

  /* 购物车主要内容区CSS */
  .shoppingCart .content {
    width: 1225px;
    margin: 0 auto;
    background-color: #fff;
  }

  .shoppingCart .content ul {
    background-color: #fff;
    color: #424242;
    line-height: 85px;
  }
  /* 购物车表头及CSS */
  .shoppingCart .content ul .header {
    height: 85px;
    padding-right: 26px;
    color: #424242;
  }
  .shoppingCart .content ul .product-list {
    height: 85px;
    padding: 15px 26px 15px 0;
    border-top: 1px solid #e0e0e0;
  }
  .shoppingCart .content ul .pro-check {
    float: left;
    height: 85px;
    width: 110px;
  }
  .shoppingCart .content ul .pro-check .el-checkbox {
    font-size: 16px;
    margin-left: 24px;
  }
  .shoppingCart .content ul .pro-img {
    float: left;
    height: 85px;
    width: 120px;
  }
  .shoppingCart .content ul .pro-img img {
    height: 80px;
    width: 80px;
  }
  .shoppingCart .content ul .pro-name {
    float: left;
    width: 380px;
  }
  .shoppingCart .content ul .pro-name a {
    color: #424242;
  }
  .shoppingCart .content ul .pro-name a:hover {
    color: #ff6700;
  }
  .shoppingCart .content ul .pro-price {
    float: left;
    width: 140px;
    padding-right: 18px;
    text-align: center;
  }
  .shoppingCart .content ul .pro-num {
    float: left;
    width: 150px;
    text-align: center;
  }
  .shoppingCart .content ul .pro-total {
    float: left;
    width: 120px;
    padding-right: 81px;
    text-align: right;
  }
  .shoppingCart .content ul .pro-total-in {
    color: #ff6700;
  }
  .shoppingCart .content ul .pro-action {
    float: left;
    width: 80px;
    text-align: center;
  }
  .shoppingCart .content ul .pro-action i:hover {
    color: #ff6700;
  }
  /* 购物车表头及CSS END */

  /* 购物车底部导航条CSS */
  .shoppingCart .cart-bar {
    width: 1225px;
    height: 50px;
    line-height: 50px;
    background-color: #fff;
  }
  .shoppingCart .cart-bar .cart-bar-left {
    float: left;
  }
  .shoppingCart .cart-bar .cart-bar-left a {
    line-height: 50px;
    margin-left: 32px;
    color: #757575;
  }
  .shoppingCart .cart-bar .cart-bar-left a:hover {
    color: #ff6700;
  }
  .shoppingCart .cart-bar .cart-bar-left .sep {
    color: #eee;
    margin: 0 20px;
  }
  .shoppingCart .cart-bar .cart-bar-left .cart-total {
    color: #757575;
  }
  .shoppingCart .cart-bar .cart-bar-left .cart-total-num {
    color: #ff6700;
  }
  .shoppingCart .cart-bar .cart-bar-right {
    float: right;
  }
  .shoppingCart .cart-bar .cart-bar-right .total-price-title {
    color: #ff6700;
    font-size: 14px;
  }
  .shoppingCart .cart-bar .cart-bar-right .total-price {
    color: #ff6700;
    font-size: 30px;
  }
  .shoppingCart .cart-bar .cart-bar-right .btn-primary {
    float: right;
    width: 200px;
    text-align: center;
    font-size: 18px;
    margin-left: 50px;
    background: #ff6700;
    color: #fff;
  }
  .shoppingCart .cart-bar .cart-bar-right .btn-primary-disabled {
    float: right;
    width: 200px;
    text-align: center;
    font-size: 18px;
    margin-left: 50px;
    background: #e0e0e0;
    color: #b0b0b0;
  }
  .shoppingCart .cart-bar .cart-bar-right .btn-primary:hover {
    background-color: #f25807;
  }
  /* 购物车底部导航条CSS END */
  /* 购物车主要内容区CSS END */

  /* 购物车为空的时候显示的内容CSS */
  .shoppingCart .cart-empty {
    width: 1225px;
    margin: 0 auto;
  }
  .shoppingCart .cart-empty .empty {
    height: 300px;
    padding: 0 0 130px 558px;
    margin: 65px 0 0;
    background: url(../../imgs/cart-empty.png) no-repeat 124px 0;
    color: #b0b0b0;
    overflow: hidden;
  }
  .shoppingCart .cart-empty .empty h2 {
    margin: 70px 0 15px;
    font-size: 36px;
  }
  .shoppingCart .cart-empty .empty p {
    margin: 0 0 20px;
    font-size: 20px;
  }
  /* 购物车为空的时候显示的内容CSS END */
  /*分页*/
  .page-bar {
    height: 40px;
    width: 100%;
    margin: 20px auto;
  }
  .page-bar ul {
    margin: 0 auto;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
  li {
    /* height: 34px; */
    margin: 0px;
    padding: 0px;
  }
  li {
    list-style: none;
  }
  .page-bar li:first-child > a {
    margin-left: 0px;
  }
  .page-bar a {
    border: 1px solid #ddd;
    text-decoration: none;
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #5d6062;
    cursor: pointer;
    margin-right: 20px;
  }
  .page-bar a:hover {
    background-color: #eee;
  }
  .page-bar a.banclick {
    cursor: not-allowed;
  }
  .page-bar .active a {
    color: #fff;
    cursor: default;
    background-color: #e96463;
    border-color: #e96463;
  }
  .page-bar i {
    font-style: normal;
    color: #d44950;
    margin: 0px 4px;
    font-size: 12px;
  }
</style>
